package core.schedule.snake.schedule.core;

import java.io.File;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import core.schedule.snake.data.domain.DsfaTask;
import core.schedule.snake.schedule.impl.TaskTypeInterface;
import core.tool.common.SystemInfo;
import core.tool.log.log4j.EasyLogger;

public class ScanService {
	
	public static Map<String, TaskTypeInterface> typeMap=null;
	
	public static TaskTypeInterface getTaskTypeInterface(DsfaTask dsfaTask,TaskInfo taskInfo) {
		if(typeMap==null) {
			scanPackage(taskInfo.getPackagePath());
		}
		String taskType=dsfaTask.getTaskType();
		TaskTypeInterface taskTypeInterface=typeMap.get(taskType);
		return taskTypeInterface;
	}
	
	public static void scanPackage(String packagePath) {
		typeMap=new HashMap<String, TaskTypeInterface>();
		/**
		 * 获取项目路径...
		 */
//		String allClasssPath=Thread.currentThread().getContextClassLoader().getResource("").toString();
		String allClasssPath=SystemInfo.ROOT_PATH+"WEB-INF/classes";
		String folder=allClasssPath+"\\"+packagePath.replace(".", "\\");
		EasyLogger.debug("实现类扫包目录："+folder);
		File folderFile=new File(folder);		
		handlerDirectory(folderFile,packagePath);
	}	

	private static void handlerDirectory(File folderFile,String packagePath) {
		try {
			File[] files = folderFile.listFiles();
			for (File file : files) {
				if (file.isDirectory()) {
					handlerDirectory(file, packagePath);
				} else if (file.isFile()) {
					String absolutePath = file.getAbsolutePath();
					if (!absolutePath.endsWith(".class"))continue;
					int begin = absolutePath.indexOf(packagePath.replace(".", "\\"));
					int end = absolutePath.lastIndexOf(".");
					String thisClassPath = absolutePath.substring(begin, end).replace("\\", ".");
					Class cla = Class.forName(thisClassPath);
					scanAnnotationForRequestMapping(cla);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void  scanAnnotationForRequestMapping(Class cla) throws InstantiationException, IllegalAccessException {
		Annotation[] classAnnotations=cla.getAnnotations();		
		for(Annotation annotation : classAnnotations) {
			if(annotation instanceof TaskType) {
				TaskType taskType=(TaskType)annotation;
				String value=taskType.value();
				typeMap.put(value, (TaskTypeInterface) cla.newInstance());
			}
		}		
	}	
}
